/*
 * @Author: linyi
 * @Date: 2019-03-13 10:41:17
 * @Last Modified by: linyi
 * @Last Modified time: 2019-03-18 14:09:54
 */

import React, { Component } from 'react'
import { request } from 'Utils'
import { order as OrderApi, orderCenter as OrderCenter } from 'ApiMapper'
import { CommonDetail } from 'Comps'
import moment from 'moment'
import { connect } from 'react-redux'
import { actions } from '@/layout/index'

const { ORDER_STATUS } = OrderApi
const { API_GET_REFUND_FULL_ORDER, API_GET_REFUND_PART_ORDER } = OrderCenter

class App extends Component {
  constructor() {
    super()
    this.state = {
      pageIndex: 1, // 当前页
      pageSize: 50, // 每页条数
      searchParams: {}, // 查询条件
      isPartial: 0, // 不是部分退
      detailData: {},
      orderStatusMap: new Map(),
    }

    this.fullFundConfig = {
      formItems: [
        {
          title: '基本信息',
          list: [
            {
              label: '退货申请号',
              placeholder: '无',
              type: 'item',
              required: true,
              decorator: 'id',
            },
            {
              label: '订单号码',
              placeholder: '无',
              type: 'item',
              required: true,
              decorator: 'orderCode',
            },
            {
              label: '退款原因',
              placeholder: '无',
              type: 'item',
              required: true,
              decorator: 'reason',
            },
            {
              label: '凭证图片',
              placeholder: '无',
              type: 'image',
              required: true,
              decorator: 'picturesList',
            },
          ],
        },
      ],
    }

    this.partFundConfig = {
      formItems: [
        {
          title: '基本信息',
          list: [
            {
              label: '退货申请号',
              placeholder: '无',
              type: 'item',
              required: true,
              decorator: 'id',
            },
            {
              label: '订单号码',
              placeholder: '无',
              type: 'item',
              required: true,
              decorator: 'orderCode',
            },
            {
              label: '退款原因',
              placeholder: '无',
              type: 'item',
              required: true,
              decorator: 'reason',
            },
            {
              label: '凭证图片',
              placeholder: '无',
              type: 'image',
              required: true,
              decorator: 'picturesList',
            },
          ],
        },
        {
          title: '退款商品信息',
          list: [
            {
              label: '表格',
              placeholder: '无',
              type: 'table',
              decorator: 'refundGoodsInfoList',
              required: true,
              bordered: true,
              columns: [
                { title: '商品编号', dataIndex: 'id', key: 'id' },
                { title: '商品名称', dataIndex: 'foodName', key: 'foodName' },
                { title: '规格', dataIndex: 'skuId', key: 'skuId' },
                {
                  title: '单价（元）',
                  dataIndex: 'originFoodPrice',
                  key: 'originFoodPrice',
                },
                {
                  title: '购买数量',
                  dataIndex: 'refundQuantity',
                  key: 'refundQuantity',
                },
                {
                  title: '单品总价（元）',
                  dataIndex: 'originTotalPrice',
                  key: 'originTotalPrice',
                },
                {
                  title: '退款数量',
                  dataIndex: 'refundPrice',
                  key: 'refundPrice',
                },
                {
                  title: '单品退款总额（元）',
                  dataIndex: 'refundTotalPrice',
                  key: 'refundTotalPrice',
                },
              ],
            },
          ],
        },
      ],
    }
  }

  async componentDidMount() {
    const { match, changeBreadcrumb } = this.props
    const { id, isPartial } = match.params

    changeBreadcrumb(['订单中心', '退货列表', '退货详情'])

    await request(ORDER_STATUS, 'GET').then(({ result }) => {
      const orderStatusChoices = result.map(({ code, value }) => ({
        value: code,
        label: value,
      }))
      const orderStatusMap = new Map(
        orderStatusChoices.map(({ value, label }) => [value.toString(), label]),
      )
      this.setState({ orderStatusMap })
    })

    this.setState({ searchParams: { id }, isPartial }, () => this.fetchRequestData(this.state.searchParams))
  }

  /* ---------- 数据交互操作 ---------- */
  fetchRequestData = searchParams => {
    if (!searchParams) return

    Object.keys(searchParams).forEach(key => {
      const element = searchParams[key]
      if (element === '') delete searchParams[key]
    })
    searchParams = {
      ...searchParams,
      page: this.state.pageIndex,
      size: this.state.pageSize,
    }
    let api = API_GET_REFUND_FULL_ORDER
    if (this.state.isPartial === '0') {
      api = API_GET_REFUND_PART_ORDER
    }
    request(api, 'GET', { params: searchParams }).then(result => {
      if (result && result.result) {
        const { orderStatusMap } = this.state
        const {
          orderCode, orderStatus, updatedTime, refundGoodsInfoList: infoList,
        } = result.result

        const title = `美团 ${orderCode}`
        const status = orderStatusMap.get(orderStatus.toString()) || '--'
        let updateTime = updatedTime
          ? moment(updatedTime).format('YYYY/MM/DD HH:mm:ss')
          : '--'
        updateTime = `状态变更时间 ${updateTime}`
        const refundGoodsInfoList = infoList.map(
          item => ({
            ...item,
            key: item.id,
          }),
        )
        const res = {
          ...result.result,
          title,
          status,
          updateTime,
          // reason:
          //   '测试宽度测试宽度测试宽度测试宽度测试宽度测试宽度测试宽度测试宽度测试宽度测试宽度测试宽度测试宽度测试宽度',
          refundGoodsInfoList,
        }
        this.setState({
          detailData: res,
        })
      }
    })
  }

  render() {
    const { detailData, isPartial } = this.state
    return (
      <CommonDetail
        detailData={detailData}
        detailConfig={
          isPartial === '1' ? this.fullFundConfig : this.partFundConfig
        }
      />
    )
  }
}

export default connect(
  () => ({}),
  {
    changeBreadcrumb: actions.changeBreadcrumb,
  },
)(App)
